
package com.dongnam.security.auth.module.tomcat;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.security.auth.principal.RolePrincipal;
import com.dongnam.security.auth.principal.UserPrincipal;
import com.dongnam.security.auth.util.CryptUtil;


/**
 * <p> This LoginModule authenticates users with a password stored in a database.
 * 
 * It creates a new JDBC connection every time a user logins.
 * Performance may be poor if there are many login. Considering creating a persistence 
 * JDBC connection. But this would be equivalent to JDBCRealm function.
 * 
 * <p> If syniverse successfully authenticates itself,
 * a <code>RolePrincipal</code> with the syniverse's user name
 * is added to the Subject.
 * 
 * <p> This LoginModule recognizes the debug option.
 * If set to true in the login Configuration,
 * debug messages will be output to the output stream, System.out.
 *
 * @version 1.01
 */
public class DBLoginModule implements LoginModule {

	private static Logger logger = LoggerFactory.getLogger(DBLoginModule.class);
    // initial state
    private Subject subject;
    private CallbackHandler callbackHandler;
    private Map sharedState;
    private Map options;

    // configurable option
    private boolean debug = false;

    // the authentication status
    private boolean succeeded = false;
    private boolean commitSucceeded = false;

    // username and userGroup(ie. role)
    private String username;
    
    private Set<String>	userGroup = new HashSet<String>();
    
    private String connUrl;
    private String connUsername;
    private String connPassword;
	private String userTableName;
	private String nameColumn;
	private String passwordColumn;
    /**
     * Initialize this <code>LoginModule</code>.
     *
     * <p>
     *
     * @param subject the <code>Subject</code> to be authenticated. <p>
     *
     * @param callbackHandler a <code>CallbackHandler</code> for communicating
     *			with the end user (prompting for user names and
     *			passwords, for example). <p>
     *
     * @param sharedState shared <code>LoginModule</code> state. <p>
     *
     * @param options options specified in the login
     *			<code>Configuration</code> for this particular
     *			<code>LoginModule</code>.
     */
    public void initialize(Subject subject, 
	           CallbackHandler callbackHandler,
			 Map<java.lang.String, ?> sharedState, 
			 Map<java.lang.String, ?> options) {
 
		this.subject = subject;
		this.callbackHandler = callbackHandler;
		this.sharedState = sharedState;
		this.options = options;
	
		// initialize any configured options.  You can add any options here, such as the DB connection to audit trail
		debug = "true".equalsIgnoreCase((String)options.get("debug"));		
		
		connUrl = (String)options.get("connection.url");
		connUsername = (String)options.get("connection.username");
		connPassword = (String)options.get("connection.password");
		userTableName = (String)options.get("userTableName");
		nameColumn = (String)options.get("nameColumn");
		passwordColumn = (String)options.get("passwordColumn");
		
		logger.debug("connection.url = " + connUrl);
		logger.debug("connection.username = " + connUsername);
		logger.debug("connection.password = " + connPassword);
		logger.debug("userTableName = " + userTableName);
		logger.debug("nameColumn = " + nameColumn);
		logger.debug("passwordColumn = " + passwordColumn);
		
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    // This method should be slow (relatively)
    public String getPasswordFromDB(String username) {
        Connection con = null;
        PreparedStatement pstmt = null;   
      
        try {
        	con = DriverManager.getConnection(connUrl, connUsername, connPassword);
        	String statementStr = String.format("SELECT %s, %s FROM %s WHERE %1$s = ?", nameColumn, passwordColumn, userTableName);
        	logger.debug("query statement = {}", statementStr);
        	pstmt = con.prepareStatement(statementStr);
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();
            if(rs.next()){
            	String password = rs.getString(passwordColumn);
//            	logger.debug("retrieved password = {}", password);
            	return password;
            }else{
//            	logger.debug("0 row returned");
            }
        }catch(Exception e){
        	logger.error("get password from db", e);
        }finally{
        	try{
        		if (pstmt != null) pstmt.close();
        	}catch(Exception e){
            	logger.error("close prepared statement", e);
        	}
        	try{
        		if (con != null) con.close();
        	}catch(Exception e){
            	logger.error("close connection", e);
        	}
        }
        return null;
    }

    /**
     * Authenticate the user verifying the password with that in DB
     *
     * <p>
     *
     * @return true in all cases since this <code>LoginModule</code>
     *		should not be ignored.
     *
     * @exception FailedLoginException if the authentication fails. <p>
     *
     * @exception LoginException if this <code>LoginModule</code>
     *		is unable to perform the authentication.
     */
    public boolean login() throws LoginException {
		// prompt for a user name and password
		if (callbackHandler == null) {
		    throw new LoginException("Error: no CallbackHandler available " +
				"to garner authentication information from the user");
		}
		
		Callback[] callbacks = new Callback[2];
		callbacks[0] = new NameCallback("user name: ");
		callbacks[1] = new PasswordCallback("password: ", false);
	 
	    char[] passwordChar;
		try {
		    callbackHandler.handle(callbacks);
		    username = ((NameCallback)callbacks[0]).getName();
		    char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword();
		    if (tmpPassword == null) {
		    	// treat a NULL password as an empty password
		    	tmpPassword = new char[0];
		    }
		    passwordChar = new char[tmpPassword.length];
		    System.arraycopy(tmpPassword, 0,
				passwordChar, 0, tmpPassword.length);
		    ((PasswordCallback)callbacks[1]).clearPassword();
	 
		} catch (java.io.IOException ioe) {
		    throw new LoginException(ioe.toString());
		} catch (UnsupportedCallbackException uce) {
		    throw new LoginException("Error: " + uce.getCallback().toString() +
			" not available to garner authentication information " +
			"from the user");
		}
		String password = new String(passwordChar);
		
		// verify the username/password
		succeeded = false;
		String requiredPassword = getPasswordFromDB(username);
		if(requiredPassword == null){
			// user not found
			logger.debug("user not found, user = {}", username);
		    username = null; // necessary
	    	throw new FailedLoginException("user not found: username = " + username);
		}else{
			try {
				if (CryptUtil.verify(password, requiredPassword)) {
					logger.info("authentication succeeded: user = {}", username);
					userGroup.clear();
				    userGroup.add("syniverse-user");
					succeeded = true;
				}else{
					logger.debug("authentication failed: user = {}", username);
				}
			} catch (Exception e) {
				logger.error("verify password error", e);
			}
		}
		logger.debug("return {}", succeeded?"success":"failed");
		return succeeded;
    }

    /**
     * <p> This method is called if the LoginContext's
     * overall authentication succeeded
     * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
     * succeeded).
     *
     * <p> If this LoginModule's own authentication attempt
     * succeeded (checked by retrieving the private state saved by the
     * <code>login</code> method), then this method associates a
     * <code>UserPrincipal</code>
     * with the <code>Subject</code> located in the
     * <code>LoginModule</code>.  If this LoginModule's own
     * authentication attempted failed, then this method removes
     * any state that was originally saved.
     *
     * <p>
     *
     * @exception LoginException if the commit fails.
     *
     * @return true if this LoginModule's own login and commit
     *		attempts succeeded, or false otherwise.
     */
    public boolean commit() throws LoginException {
		if (succeeded == false) {
		    return false;
		} else {
		    // add a Principal (authenticated identity)
		    // to the Subject
	
			subject.getPrincipals().clear();
			
			subject.getPrincipals().add(new UserPrincipal(username));
		    // assume the user we authenticated is the UserPrincipal
		    RolePrincipal rolePrincipal;
			for (String ug : this.userGroup) {
			    rolePrincipal = new RolePrincipal(ug);
			    if (!subject.getPrincipals().contains(rolePrincipal)){
			    	subject.getPrincipals().add(rolePrincipal);
			    }
			}
	
			logger.debug("added " + userGroup + " to Subject");
	
		    commitSucceeded = true;
		    return true;
		}
    }

    /**
     * <p> This method is called if the LoginContext's
     * overall authentication failed.
     * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
     * did not succeed).
     *
     * <p> If this LoginModule's own authentication attempt
     * succeeded (checked by retrieving the private state saved by the
     * <code>login</code> and <code>commit</code> methods),
     * then this method cleans up any state that was originally saved.
     *
     * <p>
     *
     * @exception LoginException if the abort fails.
     *
     * @return false if this LoginModule's own login and/or commit attempts
     *		failed, and true otherwise.
     */
    public boolean abort() throws LoginException {
    	if (succeeded == false) {
    		return false;
		} else if (succeeded == true && commitSucceeded == false) {
		    // login succeeded but overall authentication failed
		    succeeded = false;
		    username = null;
		    userGroup.clear();
		} else {
		    // overall authentication succeeded and commit succeeded,
		    // but someone else's commit failed
		    logout();
		}
		return true;
    }

    /**
     * Logout the user.
     *
     * <p> This method removes the <code>UserPrincipal</code> & <code>RolePrincipal</code>
     * that was added by the <code>commit</code> method.
     *
     * <p>
     *
     * @exception LoginException if the logout fails.
     *
     * @return true in all cases since this <code>LoginModule</code>
     *          should not be ignored.
     */
    public boolean logout() throws LoginException {
    	logger.debug( username + " logout");
		subject.getPrincipals().clear();
		succeeded = false;
		commitSucceeded = false;
		username = null;
		userGroup.clear();

		return true;
    }
    
}
